﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FineSoft.Models
{
	public class Directory : FileItem
	{
		private System.Collections.ObjectModel.ObservableCollection<Directory> _Directories;
		public System.Collections.ObjectModel.ObservableCollection<Directory> Directories
		{
			get
			{
				if (this._Directories == null)
					this._Directories = new System.Collections.ObjectModel.ObservableCollection<Directory>();
				return this._Directories;
			}
		}

		private System.Collections.ObjectModel.ObservableCollection<File> _Files;
		public System.Collections.ObjectModel.ObservableCollection<File> Files
		{
			get
			{
				if (this._Files == null)
					this._Files = new System.Collections.ObjectModel.ObservableCollection<File>();
				return this._Files;
			}
		}

		public System.Collections.Generic.IEnumerable<FileItem> Children
		{
			get
			{
				return this.Directories.OfType<FileItem>().Concat(this.Files.OfType<FileItem>());
			}
		}

		private string _ExtDirectory;
		public string ExtDirectory
		{
			get
			{
				if (this._ExtDirectory == null)
				{
					this._ExtDirectory = this.BaseDirectory + ".Ext\\";
					if (!System.IO.Directory.Exists(this._ExtDirectory))
					{
						System.IO.Directory.CreateDirectory(this._ExtDirectory);
						new System.IO.DirectoryInfo(this._ExtDirectory).Attributes |= System.IO.FileAttributes.Hidden;
					}
				}
				return this._ExtDirectory;
			}
		}

		public override string Name
		{
			get
			{
				return System.IO.Path.GetFileNameWithoutExtension(this.Path.TrimEnd('\\'));
			}
		}

		public Directory(string path)
		{
			this.Initialize(this, path);
		}

		protected Directory(Directory baseDirectory, string path)
		{
			this.Initialize(baseDirectory, path);
		}

		protected void Initialize(Directory baseDirectory, string path)
		{
			this.BaseDirectory = baseDirectory;
			this.Path = path;
			foreach (string directoryPath in System.IO.Directory.GetDirectories(path))
				this.Directories.Add(new Directory(baseDirectory, directoryPath));
			foreach (string filePath in System.IO.Directory.GetFiles(path))
				this.Files.Add(new File(baseDirectory, filePath));
			for (int i = 0; i < this.Files.Count; i++)
			{
				File file = this.Files[0];
				if (file.AssociatedFiles.Length == 0)
					continue;
				foreach (File associatedFile in this.Files)
				{
					File existedFile = this.Files.FirstOrDefault(f => f.Path == associatedFile.Path);
					if (existedFile == null)
						continue;
					int index = this.Files.IndexOf(existedFile);
					this.Files.RemoveAt(index);
					if (i > index)
						i--;
				}
			}
		}
	}
}